import { Injectable, ForbiddenException } from '@nestjs/common';
import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'
import { randomUUID } from 'node:crypto'
import { Cam } from './schemas/cam.schema';
import { CreateCamDto } from './dto/create-cam.dto';
import { CamDto } from './dto/cam.dto';
import { GroupsService } from './groups.service';

interface CCam extends CreateCamDto {
	id : string
}

@Injectable()
export class WebCamsService {
	constructor(@InjectModel(Cam.name) private camModel : Model<Cam>, private groupsService : GroupsService) { }

	async insertMany(data : CreateCamDto[]) : Promise<any> {
		for (const item of data) {
			const cam = item as CCam
			const info = (await this.camModel
				.findOne({ name: cam.name })
				.exec())?.toObject()
			if (info) throw new ForbiddenException('已存在')
			else cam.id = randomUUID()
		}
		const created = this.camModel.insertMany(data)
		return created
	}

	async handleData(data : any) : Promise<any> {
		if (Array.isArray(data)) return Promise.all(data.map(d => this.handleData(d)))
		
		const group = (await this.groupsService.findOne({ id: data.group } as any)).toObject()
		
		data = data.toObject()
		data.groupName = group?.name

		return data
	}

	async find() : Promise<any[]> {
		return this.handleData(await this.camModel.find().exec())
	}

	async findOne(data : CamDto) : Promise<any> {
		return this.handleData(await this.camModel.findOne(data).exec())
	}

	async updateOne(data : any) {
		const _id = data._id
		Reflect.deleteProperty(data, '_id')
		return this.camModel.updateOne({ _id }, { $set: data }).exec()
	}

	async deleteOne(data : any) {
		if (data) {
			const deleted = await this.camModel.deleteOne(data).exec()
			return deleted
		}
	}
}